<template>
    <div class="carousel_add">
        <h3>发布轮播图</h3>

        <!-- 轮播图预览区域 -->
        <h4 style="margin-top: 2vh;">轮播图列表</h4>
        <div class="carousel_show">
            <el-carousel indicator-position="outside">
                <el-carousel-item v-for="item in carouselListData" :key="item.Carousel_url">
                    <img :src="item.Carousel_url" alt="轮播图展示区" style="width: 100%; object-fit: cover;" />
                </el-carousel-item>
            </el-carousel>
        </div>

        <!-- 添加轮播图区域 -->
        <h4 style="margin-top: 2vh;">添加轮播图 (通过url)</h4>
        <button class="add_newcarousel" @click="addNewCarousel">添加轮播图</button>
        <div class="form_add_newcarousel" v-if="get_error">
            <div class="form_add_newcarousel_area">
                <button class="close" @click="closeForm_close"></button>
                <div class="form_add_newcarousel_content">
                    <div class="form_body">
                        <div class="imgs" type="file" @click="triggerFileInput">
                            <img :src="imagePath" style="width: 100%;height: 100%; object-fit: cover;" alt="">
                        </div>
                        <div class="form_input">
                            <input type="file" ref="fileInput" style="display: none;" @change="addimages" />
                            <div style="margin:2vh;"></div>
                            <label>图片路径：</label> <el-input show-word-limit type="text" placeholder="请添加轮播图URL"
                                v-model="imagePath" style="width: 20vw;" />
                            <div style="margin:2vh;"></div>
                            <label>图片id：</label>
                            <el-input show-word-limit type="text" placeholder="请输入id" v-model="newCarouselId"
                                style="width: 5vw; " />
                            <label>当前最大id：</label><label>{{ maxid }}</label>
                            <div style="margin:2vh;"></div>
                            <p v-if="id_check1" class="p_tips1" >提示：当前id不合理，请输入当前图片的最大id值+1</p>
                            <p v-if="id_check2" class="p_tips2" >输入正确</p>
                        </div>
                        <hr>
                        <label style="margin-left: 1vw;">添加者：</label><label>Admin@qq.com</label>
                        <div style="margin:2vh;"></div>

                        <label style="margin-left: 1vw;">添加时间：</label><label>{{ formattedDate }}</label>
                        <div style="margin:2vh;"></div>

                        <label style="margin-left: 1vw;">添加备注：</label>
                        <div style="margin:2vh;"></div>
                        <textarea class="Systeam_item_add" placeholder="请输入备注，如果备注就填我无"
                        v-model="newmessages"
                        >
                        </textarea>
                    </div>
                    <div class="form_foot">
                        <button @click="add(imagePath, newCarouselId)">添加</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="carousel_ADD_area">
            <ul>
                <li v-for="(item, index) in carouselListData" :key="index">
                    <div class="carousel_item">
                        <img :src="item.Carousel_url" alt="">
                        <div class="carousel_informations">
                            <p>图片路径</p>
                            <el-input show-word-limit type="text" style="width: 28vw;" placeholder="请输入URL"
                                v-model="item.Carousel_url" />
                            <p>图片id</p>
                            <el-input show-word-limit type="text" style="width: 5vw;" placeholder="请输入id"
                                v-model="item.Carousel_id" />
                            <label v-if="get_error">注：请查看图片id，必须为从1到n的正整数</label>
                        </div>
                        <div class="carousel_buttons">
                            <button
                                @click="change_carousel(item.originalUrl, item.originalId, item.Carousel_url, item.Carousel_id)">修改</button>
                            <button>发布</button>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { carouselAdd, carouselList, carouselModify2 } from '@/api/request'
// 定义轮播图项的类型
// 定义轮播图项的类型
interface CarouselItem {
    Carousel_url: string;
    Carousel_id: number;
    originalUrl: string;
    originalId: number;
}

// const newCarouselUrl: string = '';
const newCarouselId = ref<number>(0)

// 获取数据
// 获取轮播图列表
const carouselListData = ref<CarouselItem[]>([])
const maxid = ref<number>(0) // 定义 maxid 为响应式变量
const getCarouselList = async () => {
    try {
        const res = await carouselList()
        carouselListData.value = res.data.map((item: CarouselItem) => ({
            ...item,
            originalUrl: item.Carousel_url,
            originalId: item.Carousel_id
        }))
        // 计算并储存当前最大的id
        maxid.value = Math.max(...carouselListData.value.map(item => item.Carousel_id));
    } catch (error) {
        console.error("请求失败:", error);
    }
}
getCarouselList();

// 修改轮播图逻辑
const change_carousel = async (oldurl: string, oldid: number, newurl: string, newid: number) => {
    const token = localStorage.getItem('TOKEN')
    try {
        const res = await carouselModify2({ token, oldurl, oldid, newurl, newid });
        if (res.code == 200) {
            console.log(res);
            ElMessage({
                type: 'success',
                message: res.msg
            }

            );
            // 刷新列表
            await getCarouselList();
        } else {
            console.log(res);
            ElMessage({
                type: 'error',
                message: res.msg
            });
        }
    } catch (error) {
        console.error("修改失败:", error);
        ElMessage.error('轮播图修改失败');
    }
}

// 添加轮播图逻辑
// 定义是否显示表单控件的变量
const get_error = ref(false)

// 打开表单
const addNewCarousel = () => {
    // 显示表单控件
    get_error.value = true
}
// 关闭表单
const closeForm_close = () => {
    get_error.value = false
}

// 点击切换上传图片
const imagePath = ref('');
const fileInput = ref();

// id判断
const id_check1 = ref(false)
const id_check2 = ref(false)
// 事件处理
const formattedDate = ref('');
const triggerFileInput = () => {
    fileInput.value.click();
};

//获取备注 
const newmessages = ref('');



// 上传图片url
const addimages = (event:Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0]; // 使用可选链操作符
    if (file) {
        // 检查文件类型是否为图片
        if (file.type.startsWith('image/')) {
            imagePath.value = URL.createObjectURL(file);
            console.log('上传图片:', imagePath.value);
        } else {
            // 使用 ElMessageBox 提示用户
            ElMessageBox.alert('请选择一个图片文件', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            imagePath.value = '';
        }
    } else {
        console.log('没有选择文件');
        imagePath.value = '';
    }
};
// 添加逻辑
const add = async (imgurl: string, id: number) => {
    console.log(imgurl, id);
    // 先判断传过来的id是否等于最大id+1
    if (id == maxid.value + 1) {
        // 判断是否为空
        if (imgurl == '' || id == 0) {
            id_check1.value = true
            id_check2.value =false
        }
        // 不为空,且满足id要求
        else { 
            // 判断id是否为正整数
            if (id > 0) {
                id_check1.value = false
                id_check2.value =true
                // 先获取当前时刻
                const newdata = new Date();
                formattedDate.value= formatDate(newdata);
                // 已经获取当前时刻
                console.log(formattedDate.value)

                // 调用添加轮播图函数
            }
            else {
                id_check1.value = true
                id_check2.value =false
            }
        }
    }
    else {
        id_check1.value = true
        id_check2.value =false
    }
}
// 定义 formatDate 函数（处理时间）
const formatDate = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
}

</script>

<style lang="scss" scoped>
.carousel_add {
    max-height: 72vh;

    overflow: scroll;
    overflow-x: hidden;
    overflow-y: scroll;
    // -ms-overflow-style: none;
    /* IE 和 Edge */
    // scrollbar-width: none;
    /* Firefox */
    background-color: rgba(255, 255, 255, 0.1);

    .carousel_show {
        padding: 0px 15%;
        width: 100%;
        height: 100%;
        background-color: rgba(255, 255, 255, 0.7);
    }

    .carousel_ADD_area {
        background-color: rgba(255, 255, 255, 0.7);
        height: 52vh !important;
        // max-height: 72vh;
        padding-left: 3vw;
        overflow: scroll;
        overflow-x: hidden;

        ul {
            li {
                height: 23vh;
                overflow: hidden;
                margin: 2vh 0;

                &:hover {
                    background-color: rgba(255, 255, 255, 1);
                    outline: auto;
                }

                cursor: pointer;

                .carousel_item {
                    display: flex;

                    img {
                        width: 20vw;
                        height: 23vh;
                        z-index: 10;
                        cursor: pointer;
                        object-fit: cover;
                        display: inline-block;
                        transition: transform 0.3s ease;
                        /* 添加过渡效果 */
                        transform-origin: top left;

                        /* 设置变换原点为左上角 */
                        &:hover {
                            transform: scale(1.2);
                        }
                    }

                    .carousel_informations {
                        height: 21vh;
                        width: 34vw;
                        line-height: 3vh;
                        margin-left: 1vw;

                        input {
                            height: 30px;
                            border: 1px solid rgb(206, 206, 206);
                            width: 17vw;
                        }

                        label {
                            color: #ff2828;
                            margin-left: 1vw;
                        }
                    }

                    .carousel_buttons {
                        line-height: 21vh;

                        button {
                            display: inline-block;
                            width: 5vw;
                            height: 4vh;
                            margin: 0 1vw;
                            cursor: pointer;
                            background-color: rgb(231, 231, 231);

                            &:hover {
                                background-color: #afb4ff;
                            }
                        }
                    }
                }
            }
        }
    }

    .add_newcarousel {
        width: 7vw;
        height: 5vh;
        position: relative;
        margin-left: 67svw;
        margin-bottom: 1vh;
        cursor: pointer;
        background-color: white;

        &:hover {
            background-color: #afb4ff;
        }
    }

    .form_add_newcarousel {
        width: 100vw;
        height: 100vh;
        background-color: rgba(0, 0, 0, 0.4);
        position: absolute;
        top: 0;
        left: 0;
        z-index: 30;

        .form_add_newcarousel_area {
            width: 70vw;
            height: 74vh;
            background-color: white;
            position: relative;
            margin: 15vh auto;

            .close {
                width: 2vw;
                height: 2vw;
                cursor: pointer;
                display: block;
                position: relative;
                margin-left: 68vw;
                background-image: url(../common/images/关闭.png);
                background-size: contain;
                background-color: white;
                background-repeat: no-repeat;

                &:hover {
                    background-color: #ff0033;
                    background-image: url(../common/images/关闭2.png)
                }
            }

            .form_add_newcarousel_content {
                width: 60vw;
                background-color: rgb(233, 241, 255);
                margin: 0 auto;

                .form_body {
                    margin: 0 auto;
                    width: 60vw;
                    height: 60vh;

                    // background-color: rgb(229, 229, 229);
                    .imgs {
                        padding: 0;
                        width: 25vh;
                        height: 25vh;
                        background-image: url(../common/images/添加.png);
                        background-color: white;
                        cursor: pointer;
                        background-size: cover;
                        background-repeat: no-repeat !important;
                        margin-left: 1vw;
                        outline: 1px solid rgb(0, 0, 0);
                        display: inline-block;
                    }

                    hr {
                        width: 97%;
                    }

                    .form_input {
                        display: inline-block;
                        vertical-align: top;
                        width: 35vw;
                        height: 25vh;
                        top: 0px;
                        margin-left: 2vw;

                        label {}

                        .p_tips1 {
                            color: #ff0033;
                        }

                        .p_tips2 {
                            color: #08a900;
                        }
                    }

                    .Systeam_item_add {
                        width: 57vw;
                        margin-left: 1vw;
                        display: block;
                        height: 17vh;
                    }
                }

                .form_foot {
                    width: 60vw;
                    height: 6vh;

                    button {
                        display: inline-block;
                        width: 6vw;
                        height: 6vh;
                        margin-left: 52vw;
                        cursor: pointer;
                        background-color: rgb(247, 247, 247);
                        outline: 1px solid rgb(197, 197, 197);

                        &:hover {
                            background-color: #afb4ff;
                        }
                    }
                }
            }
        }
    }
}
</style>

<style scoped>
.carousel_ADD_area {
    position: relative;
    left: 0px;
    direction: rtl;
    /* 将方向设置为从右到左 */
    overflow-y: auto;
    /* 启用垂直滚动条 */
}

.carousel_ADD_area::-webkit-scrollbar {
    width: 7px;
    /* 滚动条的宽度 */
}

.carousel_ADD_area::-webkit-scrollbar-track {
    background: #e7e7e7;
    /* 滚动条轨道的背景颜色 */
}

.carousel_ADD_area::-webkit-scrollbar-thumb {
    background: #000000;
    /* 滚动条滑块的背景颜色 */
}

/* 确保内容的方向正确 */
.carousel_ADD_area>* {
    direction: ltr;
    /* 将内容方向设置为从左到右 */
}

.carousel_add::-webkit-scrollbar {
    width: 10px;
    /* 滚动条的宽度 */
}

.carousel_add::-webkit-scrollbar-track {
    background: #d1caff;
    /* 滚动条轨道的背景颜色 */
}

.carousel_add::-webkit-scrollbar-thumb {
    background: #a291ff;
    /* 滚动条滑块的背景颜色 */
}

.carousel_add .carousel_ADD_area {
    height: 72vh;
}
</style>